from base_restful.const import BaseInfo
from urllib import request, parse
import json


def http_post(url, param=None):
    if param is None:
        param = {}
    param = parse.urlencode(param)
    req = request.Request(__get_url(url))
    __set_header(req)
    # req.add_header('user', parse.quote(BaseInfo.user))
    with request.urlopen(req, data=param.encode('utf-8')) as f:
        r = f.read().decode('utf-8')
        return json.loads(r)


def http_put_json(url, param=None):
    if param is None:
        param = {}
    data = json.dumps(param)
    req = request.Request(__get_url(url), method='PUT')
    __set_header(req)
    req.add_header('Content-Type', 'application/json')
    # req.add_header('user', parse.quote(BaseInfo.user))
    with request.urlopen(req, data=data.encode('utf-8')) as f:
        r = f.read().decode('utf-8')
        return json.loads(r)


def http_post_json(url, param=None):
    if param is None:
        param = {}
    data = json.dumps(param)

    req = request.Request(__get_url(url))
    __set_header(req)
    # req.add_header('user', parse.quote(Const.user))
    req.add_header('Content-Type', 'application/json')
    with request.urlopen(req, data=data.encode('utf-8')) as f:
        r = f.read().decode('utf-8')
        return json.loads(r)


def http_get(url, param=None):
    if param is not None:
        url = url + '?' + parse.urlencode(param)
    req = request.Request(__get_url(url))
    __set_header(req)
    # req.add_header('user', parse.quote(Const.user))
    with request.urlopen(req) as f:
        r = f.read().decode('utf-8')
        return json.loads(r)


def http_get_str(url, param=None):
    if param is not None:
        url = url + '?' + parse.urlencode(param)

    print(url)
    req = request.Request(__get_url(url))
    __set_header(req)
    # req.add_header('user', parse.quote(Const.user))
    with request.urlopen(req) as f:
        return f.read().decode('utf-8')


def __get_url(url):
    if str(url).startswith('http://'):
        return url
    if not str(url).startswith("/"):
        url = "/" + url
    return BaseInfo.get_sys_base_url() + url


def __set_header(req):
    req.add_header('token', BaseInfo.login.get_token())
    if BaseInfo.set_header:
        u = json.dumps(BaseInfo.login.get_user(), ensure_ascii=True)
        req.add_header('user', parse.quote(u))
